package pl.edu.pk.rz.service;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public abstract class AbstractService<T> {
	private final Class<T> entityClass;

	@Autowired
	protected SessionFactory sf;

	protected AbstractService(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	@Transactional
	public List<T> listAll() {
		return sf.getCurrentSession().createQuery("from "+entityClass.getSimpleName()).list();
	}

	@Transactional
	public T create(T object) {
		return (T) sf.getCurrentSession().save(object);
	}

	@Transactional
	public T read(int id) {
		return (T) sf.getCurrentSession().get(entityClass, id);
	}

	@Transactional
	public void update(T object) {
		sf.getCurrentSession().update(object);
	}

	@Transactional
	public void delete(T object) {
		sf.getCurrentSession().delete(object);
	}
}
